import jwt
from django.shortcuts import render
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.views import APIView

from HYDPro_h2002a.settings import SECRET_KEY
from cartapp.sers import *

def check(func):
    def inner(request):
        token = request.GET.get('token')  # 先要获取token令牌
        try:
            data = jwt.decode(token, SECRET_KEY)  # 对令牌做解析
        except Exception as e:
            return Response({'msg': '身份认证失败', 'code': 401})
        uid = data['data']['uid']  # 拿到令牌中的uid
        request.uid=uid              #把uid赋值给request.id
        return func(request)           #必须要返回外部函数，否者Response没法返回信息，他只是单独调用
    return inner



class CartView(APIView):
    @method_decorator(check)     #调用装饰器，使用django提供得method_decorator，括号里面填写得是调用得装饰器名
    def get(self, request):
        uid=request.uid          #在把request.id赋值给uid
        queryset = Cart.objects.filter(user_id=uid)  # 去数据库查询 根据uid
        ser = CartListSer(queryset, many=True)  # 序列化
        return Response({'msg': '查询成功', 'data': ser.data, 'code': 200})

    @method_decorator(check) #调用装饰器，使用django提供得method_decorator，括号里面填写得是调用得装饰器名
    def post(self, request):
        uid = request.uid
        request.data['user'] = uid  # 把uid存入到request.data
        ser = CartSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加购物车成功'})
        print(ser.errors)
        return Response({'msg': '添加购物车成功'})

    @method_decorator(check)     #调用装饰器，使用django提供得method_decorator，括号里面填写得是调用得装饰器名
    def delete(self, request):
        gid = request.GET.get('gid')
        Cart.objects.filter(id=gid).delete()
        return Response({'msg': '删除成功'})
